<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
    /**
     * logged in user id
     * @var integer
     */
    private $_id;
    
    /**
     * Authenticates a user.
     * The example implementation makes sure if the username and password
     * are both 'demo'.
     * In practical applications, this should be changed to authenticate
     * against some persistent user identity storage (e.g. database).
     * @return boolean whether authentication succeeds.
     */
    public function authenticate()
    {
        $record = User::model()->findByAttributes(array('username'=>$this->username));
        if($record === NULL){
            // user doesn't exist
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        }
        else{
            if($record->password !== $record->encrypt($this->password))
                // password doesn't match
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            else{
                // username and password matched
                $this->_id = $record->id;
                if($record->lastlogin === NULL){
                    $lastLogin = time();
                }
                else{
                    $lastLogin = strtotime($record->lastlogin);
                }

                $this->setState('lastLoginTime', $lastLogin);
                $this->errorCode = self::ERROR_NONE;
            }
        }
        
        // successful return
        return !$this->errorCode;
    }
    
    /**
     * return current logged in user id
     * @return integer 
     */
    public function getId(){
        return $this->_id;
    }
}